package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Reference
    private IUserInfoCacheService userInfoCacheService;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
       //静态资源放行,如果是访问静态资源,handler就不是HandlerMethod类型的
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //不需要登录的资源就放行,也就是没有贴@LoginUser注解的资源方法
        HandlerMethod method = (HandlerMethod) handler;
        if (!(method.hasMethodAnnotation(RequiredLogin.class))) {
            return true;
        }
        //从session里面取出当前登录的用户,如果不为null就证明用户已登录,否则没有登录
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Consts.USER_INFO);
        if (user != null) {
            return true;
        }
        //拿出token查询redis里面有没有用户数据,有的话就证明已登录,并且把用户数据存到session里面
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Consts.USER_INFO_TOKEN)) {
                    String token = cookie.getValue();
                    String userInfo = userInfoCacheService.getUserInfoCache(token);
                    if (userInfo != null) {
                        session.setAttribute(Consts.USER_INFO, JSON.parseObject(userInfo, UserInfo.class));
                        return true;
                    }
                }
            }
        }
        //没登录,回到登录页面
        response.sendRedirect("/login.html");
        return false;//不放行
    }
}
